import type { PlasmoCSConfig } from "plasmo"

// 使用url:方案导入资源，Plasmo会自动处理web_accessible_resources
import htmlUrl from "url:./index_div.html"
import cssUrl from "url:./style.css"
import scriptUrl from "url:./script.js"

export const config: PlasmoCSConfig = {
  matches: ["<all_urls>"],
  all_frames: true,
  run_at: "document_idle"
}

// 注入CSS文件
async function injectCSS(cssUrl: string, name: string): Promise<void> {
  try {
    const link = document.createElement('link')
    link.rel = 'stylesheet'
    link.href = cssUrl
    document.head.appendChild(link)
    //console.log(`CSS文件注入成功: ${name}`)
  } catch (error) {
    console.error(`注入CSS文件失败 ${name}:`, error)
  }
}

// 注入JS文件
async function injectJS(jsUrl: string, name: string): Promise<void> {
  try {
    const script = document.createElement('script')
    script.src = jsUrl
    document.head.appendChild(script)
    //console.log(`JS文件注入成功: ${name}`)
  } catch (error) {
    console.error(`注入JS文件失败 ${name}:`, error)
  }
}

// 加载并注入HTML内容
async function injectHTML(): Promise<void> {
  try {
    //console.log('开始注入HTML内容到网页...')
    
    const response = await fetch(htmlUrl)
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const htmlContent = await response.text()
    //console.log('HTML内容加载成功，长度:', htmlContent.length)
    
    // 将HTML内容注入到页面body的开头
    const div = document.createElement('div')
    div.innerHTML = htmlContent
    document.body.append(div)
    //console.log('HTML内容注入完成')
    
    // 设置图片的本地路径
    setLocalImagePaths()
    
  } catch (error) {
    console.error('注入HTML内容时发生错误:', error)
  }
}

// 设置本地图片路径
function setLocalImagePaths(): void {
  try {
    // 设置主图标
    const mainIcon = document.getElementById('main-icon_table0918') as HTMLImageElement
    if (mainIcon) {
      mainIcon.src = chrome.runtime.getURL('assets/icon-128.png')
      //console.log('主图标路径设置完成')
    }
    
    // 设置OCR图片
    const ocrImage = document.getElementById('ocr-image_table0918') as HTMLImageElement
    if (ocrImage) {
      ocrImage.src = chrome.runtime.getURL('assets/ocr.jpeg')
      //console.log('OCR图片路径设置完成')
    }
  } catch (error) {
    console.error('设置图片路径时发生错误:', error)
  }
}

// 主注入函数
async function injectContent(): Promise<void> {
  try {
    //console.log('开始注入所有内容到网页...')
    console.log('当前页面URL:', window.location.href)
    
    // 按顺序注入资源
    await injectCSS(cssUrl, 'style.css')
    await injectHTML()
    await injectJS(scriptUrl, 'script.js')
    
    //console.log('所有内容注入完成')
  } catch (error) {
    console.error('注入内容时发生错误:', error)
  }
}

// 文件上传功能 - 在content script context中运行，有Chrome API访问权限
async function handleFileUpload(fileData: string, fileName: string, fileType: string, url: string, input_xpath: string) {
  try {
    // 通过background script发送请求
    const response = await new Promise((resolve, reject) => {
      chrome.runtime.sendMessage({
        action: 'uploadFile',
        data: {
          url: url,
          fileData: fileData,
          fileName: fileName,
          fileType: fileType,
          input_xpath: input_xpath
        }
      }, (response) => {
        if (chrome.runtime.lastError) {
          reject(new Error(chrome.runtime.lastError.message));
        } else if (response.success) {
          resolve(response.data);
        } else {
          reject(new Error(response.error));
        }
      });
    });

    // 发送成功事件回页面
    window.dispatchEvent(new CustomEvent('uploadSuccess', { 
      detail: { data: response, fileName: fileName } 
    }));

  } catch (error) {
    console.error('Upload error in content script:', error);
    // 发送错误事件回页面
    window.dispatchEvent(new CustomEvent('uploadError', { 
      detail: { error: error.message, fileName: fileName } 
    }));
  }
}

// 监听来自页面的上传请求
window.addEventListener('requestUpload', (event: any) => {
  const { fileData, fileName, fileType, url,input_xpath } = event.detail;
  handleFileUpload(fileData, fileName, fileType, url, input_xpath);
});

// 等待DOM加载完成后执行注入
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', injectContent)
} else {
  // DOM已经加载完成
  injectContent()
}
